﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OpenSource.SpreadsheetFactory.Internal.Csv
{
    internal class CsvGenerator<T> : SpreadsheetGenerator<T>
    {
        public CsvGenerator(IEnumerable<T> source)
            : base(source)
        {
        }

        internal override byte[] GenerateSpreadsheet()
        {
            StringBuilder sb = new StringBuilder();
            CreateHeader(sb);
            CreateBody(sb);
            return Encoding.UTF8.GetBytes(sb.ToString());
        }

        private void CreateHeader(StringBuilder sb)
        {
            bool first = true;
            foreach (Column<T> column in Columns)
            {
                if (first) first = false;
                else sb.Append(",");

                AppendObject(column.Title, sb);
            }
            sb.AppendLine();
        }

        private void CreateBody(StringBuilder sb)
        {
            foreach (T item in Source)
            {
                bool first = true;
                foreach (Column<T> column in Columns)
                {
                    if (first) first = false;
                    else sb.Append(",");

                    AppendObject(column.GetColumnValue(item), sb);
                }
                sb.AppendLine();
            }
        }

        private static void AppendObject(object o, StringBuilder sb)
        {
            AppendObject(o.ToString(), sb);
        }

        private static void AppendObject(string str, StringBuilder sb)
        {
            sb.Append("\"" + str.Replace("\"", "\"\"") + "\"");
        }
    }
}
